package sms

import (
	"encoding/json"
	"errors"
	"strings"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v5/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credential "github.com/aliyun/credentials-go/credentials"

	"github.com/runningwater/gohub/pkg/config"
	"github.com/runningwater/gohub/pkg/logger"
)

type AliyunDriver struct {
}

// Send 实现短信驱动接口，通过阿里云服务发送短信
// 参数：
//
//	phone : 接收方手机号码（格式：国际区号+手机号，示例：+8613711112222）
//	message : 短信消息体，包含模板ID和模板参数
//	config : 阿里云访问配置（需包含 access_key_id 和 access_key_secret）
//
// 返回值：
//
//	bool : 发送成功返回 true，失败返回 false
func (a *AliyunDriver) Send(phone string, message Message, config map[string]string) bool {
	const moduleName = "短信[阿里云]"
	client, err := createClient()
	if err != nil {
		logger.ErrorString(moduleName, "创建阿里云客户端失败", err.Error())
		return false
	}
	templateParam, err := json.Marshal(message.Data)
	if err != nil {
		logger.ErrorString(moduleName, "解析模板参数失败", err.Error())
		return false
	}

	request := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),                   // 接收手机号
		SignName:      tea.String(config["sign_name"]),     // 短信签名
		TemplateCode:  tea.String(config["template_code"]), // 模板ID
		TemplateParam: tea.String(string(templateParam)),   // JSON格式的模板参数
	}

	logger.DebugJSON(moduleName, "请求内容", request)

	response, _e := sendSms(client, request, &util.RuntimeOptions{})
	if _e != nil {
		logger.ErrorString(moduleName, "发送失败", _e.Error())
		var e = &tea.SDKError{}
		var _t *tea.SDKError
		if errors.As(_e, &_t) {
			e = _t
		}

		// 错误消息
		if e.Message != nil {
			logger.DebugJSON(moduleName, "错误消息", tea.StringValue(e.Message))
		}

		// 诊断地址
		var data any
		d := json.NewDecoder(strings.NewReader(tea.StringValue(e.Data)))
		err := d.Decode(&data)
		if err != nil {
			return false
		}
		if m, ok := data.(map[string]any); ok {
			recommend := m["Recommend"]
			logger.DebugJSON(moduleName, "诊断地址", recommend)
		}

		return false
	}

	// 发送成功
	logger.DebugJSON(moduleName, "接口响应", response.Body)
	logger.DebugJSON(moduleName, "发送成功", "短信发送成功")

	return true
}

func createClient() (*dysmsapi20170525.Client, error) {
	credentials, err := credential.NewCredential(nil)
	if err != nil {
		return nil, err
	}

	conf := &openapi.Config{
		Credential:      credentials,
		Endpoint:        tea.String("dysmsapi.aliyuncs.com"),
		AccessKeyId:     tea.String(config.GetString("sms.aliyun.access_key_id")),
		AccessKeySecret: tea.String(config.GetString("sms.aliyun.access_key_secret")),
	}

	return dysmsapi20170525.NewClient(conf)
}

func sendSms(client *dysmsapi20170525.Client,
	request *dysmsapi20170525.SendSmsRequest,
	runtime *util.RuntimeOptions) (_result *dysmsapi20170525.SendSmsResponse, _err error) {
	defer func() {
		if r := tea.Recover(recover()); r != nil {
			_err = r
		}
	}()
	return client.SendSmsWithOptions(request, runtime)
}
